package idiolect.webstorage;

import idiolect.core.IOUtil;

import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;

public class TopicListTask implements Callable<List<TopicInfo>> {
    private static final TopicListTask INSTANCE = new TopicListTask();

    public static synchronized TopicListTask getInstance() {
        return INSTANCE;
    }

    public java.util.List<TopicInfo> call() throws Exception {
        byte[] content = IOUtil.getContent(new URL("http://code.google.com/p/idiolect/source/browse/trunk/rc/Dictionaries/"));
        String s = new String(content, "Windows-1252");
        int pos1 = s.indexOf("filelist_name");
        if (pos1 == -1)
            return null;
        int pos2 = s.indexOf("</tbody>", pos1);
        if (pos2 == -1)
            return null;
        s = s.substring(pos1, pos2);
        java.util.List<TopicInfo> list = new ArrayList<TopicInfo>();
        pos2 = 0;
        do {
            pos1 = s.indexOf("<tr", pos2);
            if (pos1 == -1)
                break;
            pos2 = s.indexOf("</tr", pos1);
            if (pos2 == -1)
                break;
            String ss = s.substring(pos1, pos2);
            TopicInfo ti = new TopicInfo();
            int e = -1;
            int b;
            e = ss.indexOf("</a", e + 1);
            b = ss.lastIndexOf(">", e);
            ti.name = ss.substring(b + 1, e);
            e = ss.indexOf("</a", e + 1);
            b = ss.lastIndexOf(">", e);
            ti.size = ss.substring(b + 1, e);
            e = ss.indexOf("</a", e + 1);
            b = ss.lastIndexOf(">", e);
            ti.revision = ss.substring(b + 1, e);
            e = ss.indexOf("</a", e + 1);
            b = ss.lastIndexOf(">", e);
            ti.date = ss.substring(b + 1, e);
            e = ss.indexOf("</a", e + 1);
            b = ss.lastIndexOf(">", e);
            ti.author = ss.substring(b + 1, e);
            list.add(ti);
        } while (true);
        return list;
    }
}
